<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="便民服务类型" prop="helpServiceType">
        <el-select v-model="queryParams.helpServiceType" placeholder="请选择便民服务类型" clearable>
          <el-option v-for="dict in help_people_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="服务时间" prop="serviceTime">
        <el-date-picker clearable v-model="queryParams.serviceTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择服务时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:HelpPeople:add']">新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:HelpPeople:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Menu" @click="handleStatistics">统计</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="HelpPeopleList" @selection-change="handleSelectionChange">

      <el-table-column label="序号" align="center" type="index" width="65" />
      <el-table-column label="部门" align="center" prop="deptName" />
      <el-table-column label="便民服务类型" align="center" prop="helpServiceType">
        <template #default="scope">
          <dict-tag :options="help_people_type" :value="scope.row.helpServiceType" />
        </template>
      </el-table-column>
      <el-table-column label="服务时间" align="center" prop="serviceTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.serviceTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="服务人员" align="center" prop="userName" />
      <el-table-column label="服务对象" align="center" prop="serviceOb" />
      <el-table-column label="服务内容" align="center" prop="serviceContent" />
      <el-table-column label="照片" align="center" prop="proof" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.proof" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:HelpPeople:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:HelpPeople:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改便民服务新版对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="HelpPeopleRef" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门" prop="deptId">
              <el-tree-select style="width: 100%;" v-model="form.deptId" :data="deptOptions" :props="{ value: 'id', label: 'label', children: 'children' }"
                value-key="id" class="margin-right" placeholder="请选择部门" check-strictly clearable />
            </el-form-item>
          </el-col><el-col :span="12">
            <el-form-item label="便民服务类型" prop="helpServiceType">
              <el-select v-model="form.helpServiceType" placeholder="请选择便民服务类型" style="width: 100%;">
                <el-option v-for="dict in help_people_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col><el-col :span="12">

            <el-form-item label="服务时间" prop="serviceTime">
              <el-date-picker clearable v-model="form.serviceTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择服务时间" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col><el-col :span="12">
            <el-form-item label="服务人员" prop="userId">
              <el-select style="width:100%" v-model="form.userId" placeholder="请选择">
                <el-option v-for="dict in usersList" :key="dict.userId" :label="dict.userName" :value="parseInt(dict.id)"></el-option>
              </el-select>
            </el-form-item>
          </el-col><el-col :span="12">
            <el-form-item label="服务对象" prop="serviceOb">
              <el-input v-model="form.serviceOb" placeholder="请输入服务对象" />
            </el-form-item>
          </el-col><el-col :span="24">
            <el-form-item label="照片" prop="proof">
              <image-upload v-model="form.proof" />
            </el-form-item>
          </el-col><el-col :span="24">
            <el-form-item label="服务内容" prop="serviceContent">
              <el-input v-model="form.serviceContent" type="textarea" placeholder="请输入内容"  :rows="6"/>
            </el-form-item>
          </el-col><el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :rows="6" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <Statistics :echartsData="statisticsData" ref="statisticsRef" @changeType="handleStatistics" />
  </div>
</template>

<script setup name="HelpPeople">
import moment from "moment";
import { listHelpPeople, getHelpPeople, delHelpPeople, addHelpPeople, updateHelpPeople, postCount } from "@/api/charge/HelpPeople";
import { getListCharge } from "@/api/charge/charge";
import { deptTreeSelect } from "@/api/system/user";
import { getCKInfo } from '@/utils/auth'
import Statistics from "./components/Statistics.vue";
const { proxy } = getCurrentInstance();
const { help_people_type } = proxy.useDict('help_people_type');

const usersList = ref([])
const HelpPeopleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const statisticsData = ref({ series: [{ data: [] }, { data: [] }], xaxis: [] })
const deptId = ref(Number(getCKInfo('deptId')))
const statisticsRef = ref()
const deptOptions = ref([])
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: deptId.value,
    helpServiceType: null,
    serviceTime: null,
    userId: null,
  },
  rules: {
    deptId: [
      { required: true, message: '部门不能为空', trigger: 'blur' },
    ],
    helpServiceType: [
      { required: true, message: '便民服务类型不能为空', trigger: 'blur' },
    ],
    serviceTime: [
      { required: true, message: '服务时间不能为空', trigger: 'blur' },
    ],
    userId: [
      { required: true, message: '服务人员不能为空', trigger: 'blur' },
    ],
    serviceOb: [
      { required: true, message: '服务对象不能为空', trigger: 'blur' },
    ],
  
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询便民服务新版列表 */
function getList() {
  loading.value = true;
  listHelpPeople(queryParams.value).then(response => {
    HelpPeopleList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
    getUsersList()
  });
};
// 表单重置
function reset() {
  form.value = {
    id: null,
    deptId: null,
    helpServiceType: null,
    serviceTime: null,
    userId: null,
    serviceOb: null,
    serviceContent: null,
    proof: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("HelpPeopleRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  form.value.deptId=deptId.value
  title.value = "添加便民服务";
}
function getUsersList() {
  getListCharge({ deptId: deptId.value }).then(response => {
    usersList.value = response.rows;
  });

}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getHelpPeople(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改便民服务";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["HelpPeopleRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateHelpPeople(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addHelpPeople(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除便民服务编号为"' + _ids + '"的数据项？').then(function () {
    return delHelpPeople(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

function handleStatistics(date) {
  // 本年  本季度  本月
  if (!date || !date.startDate) {
    date.startDate = moment().format('YYYY-MM') + '-01'
    date.endDate = moment().endOf('month').format('YYYY-MM-DD')
  }
  statisticsData.value.xaxis = []
  statisticsData.value.series[0].data = []
  postCount({
    "startTime": date.startDate,
    "endTime": date.endDate,
    // "type": type.value
  }).then(res => {
    if (res.code == 200 && res.data) {
      res.data.forEach(item => {
        statisticsData.value.xaxis.push(item.deptName)
        statisticsData.value.series[0].data.push(item.openCount)
      })
      statisticsRef.value.open();
    }
  })
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/HelpPeople/export', {
    ...queryParams.value
  }, `便民服务_${new Date().getTime()}.xlsx`)
}

getList();
getDeptTree()

</script>
